//
//  KChangePasswordDAO.m
//  KutulusLaw
//
//  Created by Mahmood1 on 12/18/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "KChangePasswordDAO.h"
#import "KBase64Encoding.h"
#import "KChangePasswordCommandDTO.h"
#import "MyApiClient.h"

@implementation KChangePasswordDAO

+ (void) changePassword:(NSString *)sessionID password:(NSString *)password block:(void (^)(NSInteger isSuccess, NSError *))block {
	KChangePasswordCommandDTO *changePasswordDTO = [[KChangePasswordCommandDTO alloc] initWithSessionID:sessionID];
	changePasswordDTO.password = password;
	
	MyApiClient *client = [MyApiClient sharedClient];
	NSMutableDictionary *parameters = [changePasswordDTO dictionary];
	NSLog(@"parameter of case api: %@", parameters);
	
	[client postPath:@"" parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
		if (responseObject) {
			responseObject = [responseObject objectFromJSONData];
			NSLog(@"Response data from case api: %@", responseObject);
			NSString *status = [[responseObject objectForKey:@"status"] uppercaseString];
			if ([status isEqualToString:@"OK"]) {
				block (OK, nil);
				return;
			} else if ([status isEqualToString:@"NOT_AUTHENTICATE"]) {
				block (NOT_AUTHENTICATE, nil);
				return;
			} else {
				block (NOT_VALID, nil);
				return;
			}
		}
		
		
		block(NOT_VALID, nil);
		
	} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
		block(NOT_VALID, error);
	}];
	
}

+ (NSString*) reverseString:(NSString *)string {
	
	if (!string) return nil;
	
	NSString* reversingString = @"";
	
	NSInteger leng = [string length];
	for (int i = leng - 1; i >= 0; i--) {
		reversingString = [reversingString stringByAppendingFormat:@"%c",[string characterAtIndex:i]];
	}
	
	return reversingString;
}
+ (NSString*) criptPassword:(NSString *)password {
	if (!password) return nil;
	if ([password length] == 0) return password;
	
	NSString *tempPassword = [KChangePasswordDAO reverseString:password];
	tempPassword = [KBase64Encoding Base64Encode:[tempPassword dataUsingEncoding:NSStringEncodingConversionAllowLossy]];
	tempPassword = [KChangePasswordDAO reverseString:tempPassword];
	
	tempPassword = [KBase64Encoding Base64Encode:[tempPassword dataUsingEncoding:NSStringEncodingConversionAllowLossy]];
	
	NSInteger lastIndex  = [tempPassword length] - 1;
	
	if ([tempPassword characterAtIndex:lastIndex] == '=') {
		tempPassword = [tempPassword substringToIndex:lastIndex];
	}
	tempPassword = [KChangePasswordDAO reverseString:tempPassword];
	
	return tempPassword;
}
@end
